package com.markhsiu.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 普通文本读取请求服务端
 * @author Mark Hsiu
 *
 */
public class CommonServer {

	
	public static void main(String[] args) {
		CommonServer server = new CommonServer();
		try {
			server.start();
		} catch (IOException e) {
			  e.printStackTrace();
		      System.exit(1);
		}
	}
	
	@SuppressWarnings("resource")
	public void start() throws IOException{
		
		ServerSocket server = new ServerSocket(8080);
		while(true){
			Socket socket = server.accept();
			System.out.println(" request " + socket.toString());
			
			LineNumberReader in = new LineNumberReader(new InputStreamReader(socket.getInputStream()));
			String lineInput;
			String requestPage = null;
			while((lineInput = in.readLine()) != null){
				System.out.println(in.getLineNumber()+"  ====  "+lineInput);
				if(in.getLineNumber() == 1){
					requestPage = lineInput.substring(lineInput.indexOf('/') + 1, lineInput.lastIndexOf(' '));
					System.out.println("request page "+requestPage);
				} else {
					if(lineInput.isEmpty()){
						System.out.println("header finished ");
						doRequestGet(requestPage, socket);
					}
				}
			}
		}
	}
	
	
	public void doRequestGet(String requestPage, Socket socket) throws IOException{
		final String WEB_ROOT = "E:\\";
		File file = new File(WEB_ROOT,requestPage);
		OutputStream out = socket.getOutputStream();
		if(file.exists()){
			InputStream fileIn = new FileInputStream(file);
					byte[] buf = new byte[fileIn.available()];
					fileIn.read(buf);
					fileIn.close();
					out.write(buf);
					out.flush();
					socket.close();
					System.out.println("response complete.");
		} else {
			String msg = "not find.. \r\n";
			String response = "HTTP/1.1 200 OK\r\n";
			response += "Server: CommonServer/0.1\r\n";
			response += "Content-Length: "+(msg.length() - 2)+"\r\n" ;
			response += "\r\n";
			response += msg;
			out.write(response.getBytes());
			out.flush();
		}
	}
	

}
